package main

import (
	"math"
	"math/rand"
	"sync"
)

type StudentIdManager struct {
	idsMap map[int]struct{}
	ids    []int
	minId  int
	mu     sync.Mutex
}

func NewStudentIdManager() *StudentIdManager {
	return &StudentIdManager{
		idsMap: make(map[int]struct{}),
		ids:    []int{},
		minId:  math.MaxInt64,
	}
}

func (s *StudentIdManager) AddId(id int) {
	s.mu.Lock()
	defer s.mu.Unlock()

	if _, ok := s.idsMap[id]; !ok {
		s.idsMap[id] = struct{}{}
		s.ids = append(s.ids, id)
	}

	if id < s.minId {
		s.minId = id
	}
}

func (s *StudentIdManager) Exist(id int) bool {
	s.mu.Lock()
	defer s.mu.Unlock()

	if _, ok := s.idsMap[id]; ok {
		return true
	}
	return false
}

func (s *StudentIdManager) Delete(id int) bool {
	s.mu.Lock()
	defer s.mu.Unlock()

	delete(s.idsMap, id)

	for k, v := range s.ids {
		if v == id {
			s.ids = append(s.ids[:k], s.ids[k+1:]...)
			break
		}
	}

	if id == s.minId {
		minId := math.MaxInt64
		for _, v := range s.ids {
			if v < minId {
				minId = v
			}
		}
		s.minId = minId
	}
	return true
}

func (s *StudentIdManager) RandomId() int {
	s.mu.Lock()
	defer s.mu.Unlock()
	return s.ids[rand.Intn(len(s.ids))]
}

func (s *StudentIdManager) MinId() int {
	s.mu.Lock()
	defer s.mu.Unlock()
	return s.minId
}
